package com.jeesite.modules.exam.notice.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.collection.CollUtil;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.ServiceException;
import com.jeesite.modules.backlog.service.DcSupBacklogService;
import com.jeesite.modules.common.dao.SysBasicDao;
import com.jeesite.modules.common.entity.SysBasicUser;
import com.jeesite.modules.exam.notice.entity.DcSupExamNoticeOrg;
import com.jeesite.modules.exam.quota.entity.DcSupExamQuotaOrg;
import com.jeesite.modules.exam.quota.entity.DcSupExamSumQuotaOrg;
import com.jeesite.modules.exam.quota.service.DcSupExamQuotaOrgService;
import com.jeesite.modules.exam.quota.service.DcSupExamSumQuotaOrgService;
import com.jeesite.modules.exam.score.service.DcSupExamScoreService;
import com.jeesite.modules.msg.entity.content.PcMsgContent;
import com.jeesite.modules.msg.utils.MsgPushUtils;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.task.action.dao.DcSupTaskActionDao;
import com.jeesite.modules.task.deploy.entity.OfficeUser;
import com.jeesite.modules.yzw.entity.MsgDetail;
import com.jeesite.modules.yzw.service.LehandYzwPushTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.exam.notice.entity.DcSupExamNotice;
import com.jeesite.modules.exam.notice.dao.DcSupExamNoticeDao;
import com.jeesite.modules.file.utils.FileUploadUtils;

/**
 * 考核任务通知表Service
 * @author xhc
 * @version 2022-05-28
 */
@Service
@Transactional(readOnly=false)
public class DcSupExamNoticeService extends CrudService<DcSupExamNoticeDao, DcSupExamNotice> {
	@Autowired
	private DcSupExamNoticeOrgService dcSupExamNoticeOrgService;
	@Autowired
	private DcSupExamQuotaOrgService dcSupExamQuotaOrgService;
	@Autowired
	private DcSupExamSumQuotaOrgService dcSupExamSumQuotaOrgService;
	@Autowired
	private  DcSupTaskActionDao dcSupTaskActionDao;
	@Autowired
	private LehandYzwPushTask lehandYzwPushTask;
	@Autowired
	private DcSupBacklogService dcSupBacklogService;

	private final static ThreadPoolExecutor smsThreadPoolExecutor = new ThreadPoolExecutor(
			1,
			10,
			60,
			TimeUnit.SECONDS,
			new LinkedBlockingQueue<>(700),
			new ThreadPoolExecutor.AbortPolicy()
	);
	/**
	 * 获取单条数据
	 * @param dcSupExamNotice
	 * @return
	 */
	@Override
	public DcSupExamNotice get(DcSupExamNotice dcSupExamNotice) {
		return super.get(dcSupExamNotice);
	}
	
	/**
	 * 查询分页数据
	 * @param dcSupExamNotice 查询条件
	 * @param
	 * @return
	 */
	@Override
	public Page<DcSupExamNotice> findPage(DcSupExamNotice dcSupExamNotice) {
		return super.findPage(dcSupExamNotice);
	}
	
	/**
	 * 查询列表数据
	 * @param dcSupExamNotice
	 * @return
	 */
	@Override
	public List<DcSupExamNotice> findList(DcSupExamNotice dcSupExamNotice) {
		return super.findList(dcSupExamNotice);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param dcSupExamNotice
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(DcSupExamNotice dcSupExamNotice) {
		Integer count = dao.findVersion(dcSupExamNotice);
		if(count > 0){
			throw new ServiceException("已有单位指标审核通过，重发通知失败");
		}
		DcSupExamNotice noticeDaoList = dao.getNoticeByExamId(dcSupExamNotice.getExamId(), "5");
		if (noticeDaoList != null && StringUtils.equals(dcSupExamNotice.getNoticeType(),"5")) {
			Integer count2 = dao.findCountDanList(dcSupExamNotice);
			if (count2 != null) {
				throw new ServiceException("当前存在正式版本发布，不可重发通知");
			}
		}
		DcSupExamNotice noticeDaoList2 = dao.getNoticeByExamId(dcSupExamNotice.getExamId(), "4");
		if (noticeDaoList2 != null && StringUtils.equals(dcSupExamNotice.getNoticeType(),"4")) {
			Integer count2 = dao.findCountDanList(dcSupExamNotice);
			if (count2 != null) {
				throw new ServiceException("当前存在正式版本发布，不可重发通知");
			}
		}

		super.save(dcSupExamNotice);
		String[] orgs = dcSupExamNotice.getNoticeOrgs().split(",");
		String[] orgNames = dcSupExamNotice.getNoticeOrgNames().split(",");

		DcSupExamNoticeOrg deOrg = new DcSupExamNoticeOrg();
		deOrg.setNoticeId(dcSupExamNotice.getId());
		dcSupExamNoticeOrgService.deleteByNoticeId(deOrg);
		for (int i = 0; i < orgs.length; i++) {
			DcSupExamNoticeOrg dcSupExamNoticeOrg = new DcSupExamNoticeOrg();
			dcSupExamNoticeOrg.setNoticeId(dcSupExamNotice.getId());
			dcSupExamNoticeOrg.setNoticeOrg(orgs[i]);
			dcSupExamNoticeOrg.setNoticeOrgName(orgNames[i]);
			dcSupExamNoticeOrg.setNoticeStatus("1");
			dcSupExamNoticeOrg.setOrgType("1");
			dcSupExamNoticeOrgService.save(dcSupExamNoticeOrg);
		}
		if(StringUtils.isNotBlank(dcSupExamNotice.getOtherOrgs())){
			String[]  otherOrgs = dcSupExamNotice.getOtherOrgs().split(",");
			String[]  otherOrgNames = dcSupExamNotice.getOtherOrgNames().split(",");
			for (int i = 0; i < otherOrgs.length; i++) {
				DcSupExamNoticeOrg dcSupExamNoticeOrg = new DcSupExamNoticeOrg();
				dcSupExamNoticeOrg.setNoticeId(dcSupExamNotice.getId());
				dcSupExamNoticeOrg.setNoticeOrg(otherOrgs[i]);
				dcSupExamNoticeOrg.setNoticeOrgName(otherOrgNames[i]);
				dcSupExamNoticeOrg.setNoticeStatus("1");
				dcSupExamNoticeOrg.setOrgType("2");
				dcSupExamNoticeOrgService.save(dcSupExamNoticeOrg);
			}
		}
		// 保存上传图片
		FileUploadUtils.saveFileUpload(dcSupExamNotice, dcSupExamNotice.getId(), "dcSupExamNotice_image");
		// 保存上传附件
		FileUploadUtils.saveFileUpload(dcSupExamNotice, dcSupExamNotice.getId(), "dcSupExamNotice_file");

		//报送通知
		if ("1".equals(dcSupExamNotice.getNoticeType())){
			sendNoticeMsg(dcSupExamNotice, orgs, "1", "您有一条关键指标报送通知待报送，请及时登录系统查看","exam_submit_key","/a/notice/dcSupExamNotice/list?noticeType=1","关键指标报送","关键指标报送通知");
		}else if("2".equals(dcSupExamNotice.getNoticeType())){
			sendNoticeMsg(dcSupExamNotice, orgs, "2", "您有一条单项指标报送通知待报送，请及时登录系统查看","exam_submit_dan","/a/notice/dcSupExamNotice/list?noticeType=2","单项指标报送","单项指标报送通知");
		}else if("5".equals(dcSupExamNotice.getNoticeType())){
			sendNoticeMsg(dcSupExamNotice, orgs, "5", "您有一条细则补充报送通知待报送，请及时登录系统查看","exam_submit_xize","/a/notice/dcSupExamNotice/list?noticeType=5","细则报送","细则补充报送通知");
		}else if("4".equals(dcSupExamNotice.getNoticeType())){
			sendNoticeMsg(dcSupExamNotice, orgs, "4", "您有一条单项指标待评分，请及时登录系统查看","exam_submit_score","/a/notice/dcSupExamNotice/dxNoticeView","单项指标评分","单项指标评分通知");
		}

	}

	private void sendNoticeMsg(DcSupExamNotice dcSupExamNotice, String[] orgs, String s, String s2,String bizType,String href,String type2,String type3) {
		if (s.equals(dcSupExamNotice.getNoticeType())) {
			String msg = s2;
			CompletableFuture.supplyAsync(() -> {
				ArrayList<OfficeUser> sysBasicUsers = new ArrayList<>();
				for (String org : orgs) {
					 List<OfficeUser> el_org = dcSupTaskActionDao.getUserByOrg("EL_ORG", org);
					sysBasicUsers.addAll(el_org);
					dcSupBacklogService.addOffice("目标考核",type2,type3,"提示信息"
							,msg.replace("登录系统","")
							,href,org
							,dcSupExamNotice.getExamId(),bizType,el_org
							,"","");
				}
				return sysBasicUsers;
			}, smsThreadPoolExecutor).thenAccept((list) -> {
				CollUtil.split(list, 20).forEach(x -> {
					CompletableFuture.runAsync(() -> {
						for (OfficeUser officeUser : x) {
							//处理发信息逻辑
//							PcMsgContent pcMsgContent = new PcMsgContent();
//							pcMsgContent.setTitle("提示信息");
//							pcMsgContent.setContent(msg);
//							MsgPushUtils.push(pcMsgContent, dcSupExamNotice.getId(), bizType, officeUser.getUserCode());
							//发送易政网消息
							MsgDetail msgDetail = new MsgDetail();
							msgDetail.setSendid(UserUtils.getUser().getUserCode());
							msgDetail.setSubjectid(officeUser.getUserCode());
							msgDetail.setMesg(msg);
							lehandYzwPushTask.pushScoreShortMsg(msgDetail);
						}
					}, smsThreadPoolExecutor);
				});
			});
		}
	}

	/**
	 * 更新状态
	 * @param dcSupExamNotice
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(DcSupExamNotice dcSupExamNotice) {
		super.updateStatus(dcSupExamNotice);
	}
	
	/**
	 * 删除数据
	 * @param dcSupExamNotice
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(DcSupExamNotice dcSupExamNotice) {
		super.delete(dcSupExamNotice);
	}

	public DcSupExamNotice getNoticeByExamId(String examId,String noticeType) {
		DcSupExamNotice notice = dao.getNoticeByExamId(examId,noticeType);
		if(notice != null){
			List<DcSupExamNoticeOrg> list = dao.getNoticeOrg(notice.getId());
			List<String> orgs = new ArrayList<>();
			List<String> orgNames = new ArrayList<>();
			list.forEach(
				dcSupExamNoticeOrg -> {
						orgs.add(dcSupExamNoticeOrg.getNoticeOrg());
						orgNames.add(dcSupExamNoticeOrg.getNoticeOrgName());
				}
			);
			notice.setNoticeOrgs(StringUtils.join(orgs,","));
			notice.setNoticeOrgNames(StringUtils.join(orgNames,","));
		}
//		if(notice != null && StringUtils.inString(noticeType,"4","5")){
//			List<DcSupExamSumQuotaOrg> list = dcSupExamSumQuotaOrgService.getOrgByExamId(examId);
//			List<String> orgs = new ArrayList<>();
//			List<String> orgNames = new ArrayList<>();
//			if(list != null && list.size() > 0) {
//				list.forEach(
//						dcSupExamNoticeOrg -> {
//							orgs.add(dcSupExamNoticeOrg.getGradeOrg());
//							orgNames.add(dcSupExamNoticeOrg.getGradeOrgName());
//						}
//				);
//				notice.setNoticeOrgs(StringUtils.join(orgs,","));
//				notice.setNoticeOrgNames(StringUtils.join(orgNames,","));
//			}
//		}
		return notice;
	}

	public Page<DcSupExamNotice> findPageVersion(DcSupExamNotice dcSupExamNotice) {
		Page<DcSupExamNotice> dcSupExamNoticePage = new Page<>();
		List<DcSupExamNotice> list = dao.findPageVersion(dcSupExamNotice);
		dcSupExamNoticePage.setList(list);
		return  dcSupExamNoticePage;
	}

    public Integer findFileStatusByVersionId(String versionId, String noticeOrgs) {
		return dao.findFileStatusByVersionId(versionId,noticeOrgs);
    }

	public Integer findFileStatus1ByVersionId(String versionId, String noticeOrgs) {
		return dao.findFileStatus1ByVersionId(versionId,noticeOrgs);
	}

	public DcSupExamNotice initNoticebyExamId(String examId, String noticeType,DcSupExamNotice dcSupExamNotice) {
		List<String> orgs = new ArrayList<>();
		List<String> orgNames = new ArrayList<>();
		if(StringUtils.equals(noticeType,"3")){
			List<DcSupExamQuotaOrg> list = dcSupExamQuotaOrgService.findOrgByExamId(examId);
			if(list != null && list.size() > 0) {
				list.forEach(
						dcSupExamNoticeOrg -> {
								orgs.add(dcSupExamNoticeOrg.getExameOrg());
								orgNames.add(dcSupExamNoticeOrg.getExameOrgName());
						}
				);
				dcSupExamNotice.setNoticeOrgs(StringUtils.join(orgs,","));
				dcSupExamNotice.setNoticeOrgNames(StringUtils.join(orgNames,","));
			}
		}
		if(StringUtils.inString(noticeType,"4","5")){
			List<DcSupExamSumQuotaOrg> list = dcSupExamSumQuotaOrgService.getOrgByExamId(examId);
			if(list != null && list.size() > 0) {
				list.forEach(
						dcSupExamNoticeOrg -> {
							orgs.add(dcSupExamNoticeOrg.getGradeOrg());
							orgNames.add(dcSupExamNoticeOrg.getGradeOrgName());
						}
				);
				dcSupExamNotice.setNoticeOrgs(StringUtils.join(orgs,","));
				dcSupExamNotice.setNoticeOrgNames(StringUtils.join(orgNames,","));
			}
		}

		return dcSupExamNotice;
	}

	public Integer findCountKeyList(String examId) {
		return  dao.findCountKeyList(examId);
	}
	@Transactional(readOnly=false)
	public void followOrg(DcSupExamNotice dcSupExamNotice) {

//		Integer count = dao.findVersion(dcSupExamNotice);
//		if(count > 0){
//			throw new ServiceException("已有单位指标审核通过，追加单位失败");
//		}
		DcSupExamNotice noticeDaoList = dao.getNoticeByExamId(dcSupExamNotice.getExamId(), "5");
		if (noticeDaoList != null && StringUtils.equals(dcSupExamNotice.getNoticeType(),"5")) {
			Integer count2 = dao.findCountDanList(dcSupExamNotice);
			if (count2 != null) {
				throw new ServiceException("当前存在正式版本发布，追加单位失败");
			}
		}
		DcSupExamNotice noticeDaoList2 = dao.getNoticeByExamId(dcSupExamNotice.getExamId(), "4");
		if (noticeDaoList2 != null && StringUtils.equals(dcSupExamNotice.getNoticeType(),"4")) {
			Integer count2 = dao.findCountDanList(dcSupExamNotice);
			if (count2 != null) {
				throw new ServiceException("当前存在正式版本发布，追加单位失败");
			}
		}

		String[] orgs = dcSupExamNotice.getNoticeOrgs().split(",");
		String[] orgNames = dcSupExamNotice.getNoticeOrgNames().split(",");
		for (int i = 0; i < orgs.length; i++) {
			DcSupExamNoticeOrg dcSupExamNoticeOrg = new DcSupExamNoticeOrg();
			dcSupExamNoticeOrg.setNoticeId(dcSupExamNotice.getId());
			dcSupExamNoticeOrg.setNoticeOrg(orgs[i]);
			dcSupExamNoticeOrg.setNoticeOrgName(orgNames[i]);
			dcSupExamNoticeOrg.setNoticeStatus("1");
			dcSupExamNoticeOrg.setOrgType("1");
			dcSupExamNoticeOrgService.save(dcSupExamNoticeOrg);
		}
		//报送通知
		if ("1".equals(dcSupExamNotice.getNoticeType())){
			sendNoticeMsg(dcSupExamNotice, orgs, "1", "您有一条关键指标报送通知待报送，请及时登录系统查看","exam_submit_key","/a/notice/dcSupExamNotice/list?noticeType=1","关键指标报送","关键指标报送通知");
		}else if("2".equals(dcSupExamNotice.getNoticeType())){
			sendNoticeMsg(dcSupExamNotice, orgs, "2", "您有一条单项指标报送通知待报送，请及时登录系统查看","exam_submit_dan","/notice/dcSupExamNotice/list?noticeType=2","单项指标报送","单项指标报送通知");
		}else if("5".equals(dcSupExamNotice.getNoticeType())){
			sendNoticeMsg(dcSupExamNotice, orgs, "5", "您有一条细则补充报送通知待报送，请及时登录系统查看","exam_submit_xize","/notice/dcSupExamNotice/list?noticeType=5","细则报送","细则补充报送通知");
		}else if("4".equals(dcSupExamNotice.getNoticeType())){
			sendNoticeMsg(dcSupExamNotice, orgs, "4", "您有一条单项指标待评分，请及时登录系统查看","exam_submit_score","notice/dcSupExamNotice/dxNoticeView","单项指标评分","单项指标评分通知");
		}
	}

    public String isNotSendMessage(String examId) {
		List<DcSupExamNotice> notSendMessage = dao.isNotSendMessage(examId);
		String str = "0";
		if(notSendMessage.size()>0){
			str="1";
		}
		return str;
    }
}